"use client"

import { Sidebar } from "@/components/sidebar"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { Input } from "@/components/ui/input"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Ruler, Search, Download, FileText, Filter, RefreshCw, AlertCircle, Loader2 } from "lucide-react"
import { useState, useEffect, useMemo } from "react"

interface MeasurementUnit {
  category: string
  unit: string
  id: number
}

export default function MeasurementUnitsPage() {
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [units, setUnits] = useState<MeasurementUnit[]>([])
  const [searchTerm, setSearchTerm] = useState("")
  const [selectedCategory, setSelectedCategory] = useState<string>("all")

  // 解析CSV数据
  const parseMeasurementUnitsCSV = () => {
    // 计量单位定义表的数据
    const csvData = [
      { category: "百分比", unit: "%" },
      { category: "冲程", unit: "mm" },
      { category: "存储容量 1", unit: "MB" },
      { category: "存储容量 2", unit: "GB" },
      { category: "存储容量 3", unit: "TB" },
      { category: "带宽 1", unit: "Gbps" },
      { category: "带宽 2", unit: "kbps" },
      { category: "电池容量", unit: "A·h" },
      { category: "电流 1", unit: "A" },
      { category: "电流 2", unit: "kA" },
      { category: "电流 3", unit: "mA" },
      { category: "电容", unit: "μF" },
      { category: "电压 1", unit: "V" },
      { category: "电压 2", unit: "kV" },
      { category: "电压 3", unit: "mV" },
      { category: "电阻", unit: "Ω" },
      { category: "电阻率", unit: "Ω ·m" },
      { category: "功率 1", unit: "W" },
      { category: "功率 2", unit: "kW" },
      { category: "功率 3", unit: "MW" },
      { category: "光功率", unit: "dBm" },
      { category: "加速度", unit: "g" },
      { category: "角度", unit: "(°)" },
      { category: "力 1", unit: "N" },
      { category: "力 2", unit: "kN" },
      { category: "力矩", unit: "N·m" },
      { category: "粒度", unit: "目" },
      { category: "流量 1", unit: "m3/s" },
      { category: "流量 2", unit: "L/s" },
      { category: "流量 3", unit: "m3/h" },
      { category: "流量 4", unit: "m3/d" },
      { category: "流量 5", unit: "104m3/d" },
      { category: "流量 6", unit: "kg/h" },
      { category: "流量 7", unit: "Nm3/h" },
      { category: "流量 8", unit: "L/min" },
      { category: "流量 9", unit: "t/h" },
      { category: "流量 10", unit: "104Nm3/d" },
      { category: "密度", unit: "kg/m3" },
      { category: "面积 1", unit: "m²" },
      { category: "面积 2", unit: "mm²" },
      { category: "面积 3", unit: "公顷" },
      { category: "质量", unit: "kg" },
      { category: "重量", unit: "t" },
      { category: "黏度", unit: "mPa · s" },
      { category: "转速", unit: "r/min" },
      { category: "浓度", unit: "mmol/L" },
      { category: "排量", unit: "L" },
      { category: "喷水强度", unit: "L/(min · m2)" },
      { category: "频率 1", unit: "Hz" },
      { category: "频率 2", unit: "MHz" },
      { category: "频率 3", unit: "GHz" },
      { category: "热值", unit: "J/m3" },
      { category: "容积 1", unit: "mL" },
      { category: "容积 2", unit: "L" },
      { category: "容积 3", unit: "m3" },
      { category: "声音强度", unit: "dB" },
      { category: "时长 1", unit: "Y" },
      { category: "时长 2", unit: "M" },
      { category: "时长 3", unit: "h" },
      { category: "时长 4", unit: "min" },
      { category: "时长 5", unit: "s" },
      { category: "时长 6", unit: "ms" },
      { category: "视在功率 1", unit: "V·A" },
      { category: "视在功率 2", unit: "kV·A" },
      { category: "数量 1", unit: "个" },
      { category: "数量 2", unit: "台" },
      { category: "数量 3", unit: "路" },
      { category: "数量 4", unit: "级" },
      { category: "数量 5", unit: "块" },
      { category: "数量 6", unit: "套" },
      { category: "数量 7", unit: "道" },
      { category: "数量 8", unit: "芯" },
      { category: "数量 9", unit: "根" },
      { category: "数量 10", unit: "部" },
      { category: "数量 11", unit: "门" },
      { category: "数量 12", unit: "只" },
      { category: "数量 13", unit: "座" },
      { category: "数量 14", unit: "圈" },
      { category: "数量 15", unit: "点" },
      { category: "数量 16", unit: "层" },
      { category: "数量 17", unit: "对" },
      { category: "数量 18", unit: "组" },
      { category: "数量 19", unit: "项" },
      { category: "无功功率", unit: "kvar" },
      { category: "效率", unit: "%" },
      { category: "压强 1", unit: "Pa" },
      { category: "压强 2", unit: "kPa" },
      { category: "压强 3", unit: "MPa" },
      { category: "压强 4", unit: "kN/m²" },
      { category: "扬程", unit: "m" },
      { category: "长度 1", unit: "mm" },
      { category: "长度 2", unit: "m" },
      { category: "长度 3", unit: "km" },
      { category: "长度 4", unit: "in" },
      { category: "长度 5", unit: "μm" },
      { category: "长度 6", unit: "cm" },
      { category: "照度", unit: "lx" },
      { category: "振动速度", unit: "mm/s" },
      { category: "转矩", unit: "N·m" },
      { category: "金额", unit: "万元" },
      { category: "衰减", unit: "dB" },
      { category: "速度 1", unit: "m/s" },
      { category: "速度 2", unit: "km/h" },
      { category: "速度 3", unit: "m/min" },
      { category: "体积 1", unit: "L" },
      { category: "体积 2", unit: "m3" },
      { category: "温度", unit: "℃" }
    ]

    return csvData.map((item, index) => ({
      ...item,
      id: index + 1
    }))
  }

  useEffect(() => {
    const loadData = () => {
      try {
        setLoading(true)
        setError(null)
        
        // 模拟加载过程
        setTimeout(() => {
          const parsedUnits = parseMeasurementUnitsCSV()
          setUnits(parsedUnits)
          setLoading(false)
        }, 500)
      } catch (err) {
        setError(err instanceof Error ? err.message : '加载计量单位数据失败')
        setLoading(false)
      }
    }

    loadData()
  }, [])

  // 获取所有分类
  const categories = useMemo(() => {
    const categorySet = new Set<string>()
    units.forEach(unit => {
      // 提取主分类（去掉数字后缀）
      const mainCategory = unit.category.replace(/\s*\d+$/, '')
      categorySet.add(mainCategory)
    })
    return Array.from(categorySet).sort()
  }, [units])

  // 过滤数据
  const filteredUnits = useMemo(() => {
    return units.filter(unit => {
      const matchesSearch = unit.category.toLowerCase().includes(searchTerm.toLowerCase()) ||
                           unit.unit.toLowerCase().includes(searchTerm.toLowerCase())
      
      if (selectedCategory === "all") {
        return matchesSearch
      }
      
      const mainCategory = unit.category.replace(/\s*\d+$/, '')
      return matchesSearch && mainCategory === selectedCategory
    })
  }, [units, searchTerm, selectedCategory])

  // 统计信息
  const stats = useMemo(() => {
    return {
      totalUnits: units.length,
      totalCategories: categories.length,
      filteredCount: filteredUnits.length
    }
  }, [units, categories, filteredUnits])

  const handleExport = () => {
    const csvContent = [
      "分类,单位",
      ...filteredUnits.map(unit => `${unit.category},${unit.unit}`)
    ].join('\n')

    const blob = new Blob(['\ufeff' + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = '计量单位定义表.csv'
    link.click()
  }

  if (loading) {
    return (
      <div className="flex h-screen bg-gray-50">
        <Sidebar />
        <div className="flex-1 flex flex-col overflow-hidden">
          <div className="flex-1 overflow-auto">
            <div className="container mx-auto py-8">
              <div className="flex items-center justify-center h-64">
                <div className="text-center">
                  <Loader2 className="h-8 w-8 animate-spin mx-auto mb-2" />
                  <p className="text-muted-foreground">正在加载计量单位数据...</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex h-screen bg-gray-50">
        <Sidebar />
        <div className="flex-1 flex flex-col overflow-hidden">
          <div className="flex-1 overflow-auto">
            <div className="container mx-auto py-8">
              <Alert variant="destructive">
                <AlertCircle className="h-4 w-4" />
                <AlertDescription>
                  {error}
                  <Button 
                    variant="outline" 
                    size="sm" 
                    className="ml-4"
                    onClick={() => window.location.reload()}
                  >
                    重试
                  </Button>
                </AlertDescription>
              </Alert>
            </div>
          </div>
        </div>
      </div>
    )
  }

  return (
    <div className="flex h-screen bg-gray-50">
      {/* 侧边栏 */}
      <Sidebar />

      {/* 主内容区域 */}
      <div className="flex-1 flex flex-col overflow-hidden">
        <div className="flex-1 overflow-auto">
          <div className="container mx-auto py-8">
            <div className="mb-8">
              <div className="flex items-center gap-4 mb-4">
                <h1 className="text-4xl font-bold text-primary">计量单位定义表</h1>
                <Badge className="blue-badge-solid">规范标准</Badge>
              </div>
              <p className="text-muted-foreground">
                标准化计量单位定义，涵盖各专业领域常用的计量单位和单位符号
              </p>
            </div>

            {/* 统计卡片 */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">总计量单位</CardTitle>
                  <Ruler className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{stats.totalUnits}</div>
                  <p className="text-xs text-muted-foreground">个计量单位</p>
                </CardContent>
              </Card>
              
              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">计量分类</CardTitle>
                  <FileText className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{stats.totalCategories}</div>
                  <p className="text-xs text-muted-foreground">个分类</p>
                </CardContent>
              </Card>

              <Card>
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">筛选结果</CardTitle>
                  <Filter className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{stats.filteredCount}</div>
                  <p className="text-xs text-muted-foreground">个匹配项</p>
                </CardContent>
              </Card>
            </div>

            {/* 搜索和筛选 */}
            <Card className="mb-6">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Search className="h-5 w-5" />
                  搜索和筛选
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="flex flex-col sm:flex-row gap-4">
                  <div className="flex-1">
                    <Input
                      placeholder="搜索计量类名或单位..."
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      className="w-full"
                    />
                  </div>
                  <div className="w-full sm:w-48">
                    <select
                      className="w-full p-2 border border-input bg-background rounded-md text-sm"
                      value={selectedCategory}
                      onChange={(e) => setSelectedCategory(e.target.value)}
                    >
                      <option value="all">所有分类</option>
                      {categories.map(category => (
                        <option key={category} value={category}>{category}</option>
                      ))}
                    </select>
                  </div>
                  <Button
                    variant="outline"
                    onClick={handleExport}
                    className="flex items-center gap-2"
                  >
                    <Download className="h-4 w-4" />
                    导出CSV
                  </Button>
                </div>
              </CardContent>
            </Card>

            {/* 数据表格 */}
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle>计量单位列表</CardTitle>
                    <CardDescription>
                      显示 {stats.filteredCount} 个计量单位（共 {stats.totalUnits} 个）
                    </CardDescription>
                  </div>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      setSearchTerm("")
                      setSelectedCategory("all")
                    }}
                  >
                    <RefreshCw className="h-4 w-4 mr-2" />
                    重置筛选
                  </Button>
                </div>
              </CardHeader>
              <CardContent>
                <div className="rounded-md border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-16">序号</TableHead>
                        <TableHead>计量类名</TableHead>
                        <TableHead>计量单位</TableHead>
                        <TableHead>主分类</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredUnits.map((unit, index) => (
                        <TableRow key={unit.id}>
                          <TableCell className="font-medium">{index + 1}</TableCell>
                          <TableCell>{unit.category}</TableCell>
                          <TableCell>
                            <Badge variant="outline" className="font-mono">
                              {unit.unit}
                            </Badge>
                          </TableCell>
                          <TableCell className="text-muted-foreground">
                            {unit.category.replace(/\s*\d+$/, '')}
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                  
                  {filteredUnits.length === 0 && (
                    <div className="text-center py-8 text-muted-foreground">
                      没有找到匹配的计量单位
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>
        </div>
      </div>
    </div>
  )
} 